import React, { useState, useEffect } from 'react';
import { Swiper, Loading } from '@nutui/nutui-react';
import { useSelector } from 'react-redux';
import { api } from '@/api/api';

const Swipers = () => {
    const [bannerList, setBannerList] = useState([]);
    const [loading, setLoading] = useState(true);
    const shopId = useSelector((state) => state.user.shopId);

    // 获取轮播图数据
    const fetchBannerData = async () => {
        try {
            setLoading(true);
            const currentShopId = shopId || localStorage.getItem("shop_id");
            if (currentShopId) {
                const response = await api.getShopPicset({
                    shopId: currentShopId,
                    type: 2 
                });
                if (response.code === 200 && response.data) {
                    setBannerList(response.data);
                }
            }
        } catch (error) {
            console.error('获取轮播图失败:', error);
            // setBannerList([
            //     'https://storage.360buyimg.com/jdc-article/NutUItaro34.jpg',
            //     'https://luxspace.obs.cn-east-3.myhuaweicloud.com/shopPicture/shop57/6.%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF.jpg',
            //     'https://storage.360buyimg.com/jdc-article/welcomenutui.jpg',
            //     'https://storage.360buyimg.com/jdc-article/fristfabu.jpg',
            // ]);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchBannerData();
    }, [shopId]);

    if (loading) {
        return (
            <div className="swipers-container">
                <div style={{ height: '200px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Loading type="spinner" />
                </div>
            </div>
        );
    }

    return (
        <div className="swipers-container">
            <Swiper
                autoPlay
                loop
                indicator
                style={{ zIndex: -1 }}
            >
                {bannerList.map((item, index) => {
                    const imageUrl = typeof item === 'string' ? item : item.content;
                    return (
                        <Swiper.Item key={item.id || index}>
                            <img 
                                src={imageUrl} 
                                alt={`banner-${index}`}
                                style={{
                                    width: '100%',
                                    height: '100%',
                                    objectFit: 'cover'
                                }}
                            />
                        </Swiper.Item>
                    );
                })}
            </Swiper>
        </div>
    );
};

export default Swipers;
